import { Sequelize } from 'sequelize-typescript'
import config from '../config'
import logger, { dbLogger } from '../logger'
import path from 'path'

//TODO，这里可以优化，从process.env中解构
//const { MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PWD, MYSQL_DB } = process.env

const seq = new Sequelize(
  config.db.db_name as string,
  config.db.db_user as string,
  config.db.db_pwd,
  {
    host: config.db.db_host,
    port: config.db.db_port as unknown as number,
    dialect: 'mysql',
    // logging: false,
    //记录日志
    logging: (msg) => dbLogger.info(msg),
    models: [
      path.join(__dirname, '..', 'model/**/*.ts'),
      path.join(__dirname, '..', 'model/**/*.js')
    ]
  }
)

const db = async () => {
  try {
    await seq.authenticate()
    //记录数据库
    logger.info('数据连接成功！')
    //  console.log('数据连接成功！')
  } catch (error) {
    logger.error('数据库连接失败！', error)
    // console.error('Unable to connect to the database:', error)
  }
}

// seq
//   .authenticate()
//   .then(() => {
//     console.log('数据库连接成功')
//   })
//   .catch((err) => {
//     console.error('数据库连接失败:')
//   })

// module.exports = seq

export default db
